package com.bsoft.bean;

import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Base64;

public class DesDecrypt {

    public static final String KEY_ALGORITHM = "DES";

    /**
     * 加密/解密算法 / 工作模式 / 填充方式
     */
    public static final String CIPHER_ALGORITHM = "DES/ECB/PKCS5PADDING";

    public static final byte[] decryptBASE64(String key) {
        return Base64.getDecoder().decode(key);
    }

    private static Key toKey(byte[] key) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException {
        // 实例化DES密钥材料
        DESKeySpec dks = new DESKeySpec(key);
        // 实例化秘密密钥工厂
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(KEY_ALGORITHM);
        // 生成秘密密钥
        SecretKey secretKey = keyFactory.generateSecret(dks);
        return secretKey;
    }

    public static byte[] decrypt(byte[] data, byte[] key) throws InvalidKeyException, NoSuchAlgorithmException,
            InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException {
        // 还原密钥
        Key k = toKey(key);
        // 实例化
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        // 初始化，设置为解密模式
        cipher.init(Cipher.DECRYPT_MODE, k);
        // 执行操作
        return cipher.doFinal(data);
    }
    public static final String decryptDes(String cryptData, String key, String charset) {
        try {
            // 把字符串解码为字节数组，并解密
            return new String(decrypt(decryptBASE64(cryptData), decryptBASE64(key)), charset);
        } catch (Exception e) {
            throw new RuntimeException("解密错误，错误信息：", e);
        }
    }
    public static void main(String[] args) {
        String content = "IUrCSA2ee0p6uVBtCOhfAg3qfoS/dQVOdFgmXYxDB4rtYD8J5yVueRsb6WmX3Jr4LN4PLCGssdUZa69VYSjH7+LSHa6u0/I6HzWvrPDZGPvMNGUjfUHsiXidi213qJuQ/oBjB/8+/LCzAt1oWGatTO+4h7sdcnPwvwyVfhhbNSrQqrvO30pHyGjjUbWRlkBW8DFmsOrvaehe5CaQScArV371cZNW/+hV4g+Yj0D5kSZIxrPQRJPfJ0oe0/cCSRi6eJ2LbXeom5BbFCwO0V+lNv1OLTMuPq9N2sIH/OjEZ8n5LkBLhqjfSZ9WhbB2fsqa3c7Lb0NTDWKsHEeKM1WZJU3OeWYB5QfEwREhtTSpe2zi1F4Xc/8ho+DG3T9+7cIMMVWbtw0g4RY=";
        String key = "rjhwdbVRaxM=";

        String raw = decryptDes(content, key, "UTF-8");


        System.out.println(raw);
    }
}